package com.edu.bhu.admin.controller.admin;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.edu.bhu.admin.domain.HouHouse;
import com.edu.bhu.admin.domain.HouRecord;
import com.edu.bhu.admin.service.IHouHouseService;
import com.edu.bhu.admin.service.IHouRecordService;
import com.edu.bhu.common.utils.DateUtils;
import com.edu.bhu.common.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.edu.bhu.common.annotation.Log;
import com.edu.bhu.common.enums.BusinessType;
import com.edu.bhu.admin.domain.HouApply;
import com.edu.bhu.admin.service.IHouApplyService;
import com.edu.bhu.common.core.controller.BaseController;
import com.edu.bhu.common.core.domain.AjaxResult;
import com.edu.bhu.common.utils.poi.ExcelUtil;
import com.edu.bhu.common.core.page.TableDataInfo;

import static com.edu.bhu.common.utils.ShiroUtils.getSysUser;

/**
 * 租房申请Controller
 * 
 * @author zhangkeyi
 * @date 2022-02-22
 */
@Controller
@RequestMapping("/admin/apply")
public class HouApplyController extends BaseController
{
    private String prefix = "admin/apply";

    @Autowired
    private IHouApplyService houApplyService;

    @Autowired
    private IHouRecordService houRecordService;

    @Autowired
    private IHouHouseService houHouseService;

    /**
     * 我的租房申请页面
     */
    @RequiresPermissions("admin:myapply:view")
    @GetMapping("/myApply")
    public String myApply()
    {
        return prefix + "/myApply";
    }

    /**
     * 我要处理的租房申请页面
     */
    @RequiresPermissions("admin:dealapply:view")
    @GetMapping("/dealApply")
    public String dealApply()
    {
        return prefix + "/dealApply";
    }

    /**
     * 查询租房申请列表
     */
    @RequiresPermissions("admin:apply:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(HouApply houApply)
    {
        startPage();
        List<HouApply> list = houApplyService.selectHouApplyList(houApply);
        return getDataTable(list);
    }

    /**
     * 查询租房申请列表(关联明细)
     */
    @RequiresPermissions("admin:apply:list")
    @PostMapping("/listWithDetail/{type}")
    @ResponseBody
    public TableDataInfo listWithDetail(@PathVariable("type")Long type, HouApply houApply)
    {
        Long userId = ShiroUtils.getSysUser().getUserId();
        if(userId != 1)//todo 管理员可以看见所有的列表 测试完再改过来
        if(type == 1){
            //查看我申请的列表
            houApply.setUserId(userId);
        }else if(type == 2){
            //查看我处理的列表
            HouHouse houHouse = new HouHouse();
            houHouse.setUserId(userId);
            houApply.setHouHouse(houHouse);
        }
        startPage();
        List<HouApply> list = houApplyService.selectHouApplyListWithDetail(houApply);
        return getDataTable(list);
    }

    /**
     * 导出租房申请列表
     */
    @RequiresPermissions("admin:apply:export")
    @Log(title = "租房申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(HouApply houApply)
    {
        List<HouApply> list = houApplyService.selectHouApplyList(houApply);
        ExcelUtil<HouApply> util = new ExcelUtil<HouApply>(HouApply.class);
        return util.exportExcel(list, "租房申请数据");
    }

    /**
     * 新增租房申请
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存租房申请
     */
    @RequiresPermissions("admin:apply:add")
    @Log(title = "租房申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Long houseId, Date date, Long timeLen)
    {
        HouApply houApply = new HouApply();
        houApply.setHouseId(houseId);
        houApply.setTime(date);
        houApply.setMonth(timeLen);
        houApply.setUserId(getSysUser().getUserId());
        return toAjax(houApplyService.insertHouApply(houApply));
    }

    /**
     * 修改租房申请
     */
    @RequiresPermissions("admin:apply:edit")
    @GetMapping("/edit/{applyId}")
    public String edit(@PathVariable("applyId") Long applyId, ModelMap mmap)
    {
        HouApply houApply = houApplyService.selectHouApplyByApplyId(applyId);
        mmap.put("houApply", houApply);
        return prefix + "/edit";
    }

    /**
     * 修改保存租房申请状态
     */
    @RequiresPermissions("admin:apply:edit")
    @Log(title = "租房申请", businessType = BusinessType.UPDATE)
    @PostMapping("/editStatus")
    @ResponseBody
    public AjaxResult editStatus(HouApply houApply)
    {
        //拿到申请记录
        HouApply entity = houApplyService.selectHouApplyByApplyId(houApply.getApplyId());

        //如果是通过申请的请求，保存租房记录，房源状态置为已出租
        if(houApply.getStatus() == 2){
            //将各种信息保存到租房记录
            HouHouse house = houHouseService.selectHouHouseByHouseId(entity.getHouseId());//拿到房屋信息
            Date endTime = DateUtils.getDatePlusDays(entity.getTime(),entity.getMonth() * 30);//计算结束日期
            BigDecimal price = house.getPrice().multiply(BigDecimal.valueOf(entity.getMonth()));//计算总价
            HouRecord houRecord = new HouRecord(entity.getHouseId(),entity.getUserId(),
                    entity.getTime(),endTime,price);
            houRecordService.insertHouRecord(houRecord);
            //房源状态置为已出租
            HouHouse houHouse = new HouHouse();
            houHouse.setHouseId(entity.getHouseId());
            houHouse.setRentStatus(2L);
            houHouseService.updateHouHouse(houHouse);

        //如果是取消审核的请求，并且当前状态是审核通过，删除租房记录，房源状态置为未出租
        } else if(houApply.getStatus() == 1 && entity.getStatus() == 2){
            //根据houseId从租房记录中删除
            houRecordService.deleteHouRecordByHouseId(entity.getHouseId());
            //房源状态置为未出租
            HouHouse houHouse = new HouHouse();
            houHouse.setHouseId(entity.getHouseId());
            houHouse.setRentStatus(1L);
            houHouseService.updateHouHouse(houHouse);
        }
        return toAjax(houApplyService.updateHouApply(houApply));
    }

    /**
     * 判断房源是否已经被出租
     */
    @GetMapping("/ifRent")
    @ResponseBody
    public String ifRent(Long applyId)
    {
        Long userId = ShiroUtils.getSysUser().getUserId();
        //拿到申请记录
        HouApply entity = houApplyService.selectHouApplyByApplyId(applyId);
        HouHouse houHouse = houHouseService.selectHouHouseByHouseId(entity.getHouseId());
        if(houHouse.getRentStatus() == 2){
            return "2";//正在出租
        }
        return "1";
    }

    /**
     * 修改保存租房申请
     */
    @RequiresPermissions("admin:apply:edit")
    @Log(title = "租房申请", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(HouApply houApply)
    {
        return toAjax(houApplyService.updateHouApply(houApply));
    }

    /**
     * 删除租房申请
     */
    @RequiresPermissions("admin:apply:remove")
    @Log(title = "租房申请", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(houApplyService.deleteHouApplyByApplyIds(ids));
    }
}
